package com.hmall.order.service.web;

import com.hmall.client.AddressClient;
import com.hmall.client.MyFeignClient;
import com.hmall.common.Address;
import com.hmall.order.service.config.MyInterceptor;
import com.hmall.order.service.pojo.Order;
import com.hmall.order.service.pojo.OrderDetail;
import com.hmall.order.service.pojo.OrderLogistics;
import com.hmall.order.service.pojo.OrderParams;
import com.hmall.order.service.service.IOrderService;
import com.hmall.order.service.service.OrderDetailService;
import com.hmall.order.service.service.OrderLogisticsService;
import com.hmall.search.common.dto.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("order")
public class OrderController {
    @Autowired
    private IOrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private OrderLogisticsService orderLogisticsService;

    @Autowired
    private MyFeignClient feignClient;

    @Autowired
    private AddressClient addressClient;

    @GetMapping("{id}")
    public Order queryOrderById(@PathVariable("id") Long orderId) {
        return orderService.getById(orderId);
    }

    @PostMapping
    public Long createOrder(@RequestBody OrderParams orderParams) {
        String id = MyInterceptor.threadLocal.get();
        Item item = feignClient.findById(orderParams.getItemId());
        Long totalFee = item.getPrice() * orderParams.getNum();
        //封装Order对象，初始status为未支付
        Order order = Order.builder().totalFee(totalFee).status(1).
                paymentType(orderParams.getPaymentType()).userId(Long.valueOf(id)).build();
        //将Order写入数据库tb_order表中
        orderService.save(order);
        OrderDetail orderDetail = OrderDetail.builder().orderId(order.getId()).price(item.getPrice()).image(item.getImage())
                .num(orderParams.getNum()).itemId(item.getId()).title(item.getName())
                .spec(item.getSpec()).build();
        orderDetailService.save(orderDetail);
        Address address = addressClient.findAddressById(orderParams.getAddressId());
        //将地址封装为OrderLogistics对象，写入tb_order_logistics表
        OrderLogistics orderLogistics = new OrderLogistics(order.getId(), null, null,
                address.getContact(), address.getMobile(), address.getProvince(), address.getCity(), address.getTown()
                , address.getStreet(), null, null);
        orderLogisticsService.save(orderLogistics);
        feignClient.updateItemStock(item.getId(),orderParams.getNum());
        return  order.getId();
    }


}
